package com.ruoyi.pay.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.pay.domain.MchApp;
import com.ruoyi.pay.service.MchAppService;
import com.ruoyi.pay.utils.JeepayKit;
import com.ruoyi.pay.vo.RequestKitBean;
import com.ruoyi.pay.websocket.server.WsPayOrderServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
* 支付测试 - 回调函数
*
* @author syf
* @site
* @date 2021/6/22 14:22
*/
@RestController
@RequestMapping("/api/anon/paytestNotify")
public class PaytestNotifyController extends BaseController {

    @Autowired private MchAppService mchAppService;

    @Autowired
    protected RequestKitBean requestKitBean;

    @Resource
    protected HttpServletRequest request;   //自动注入request

    @Resource
    protected HttpServletResponse response;  //自动注入response

  /**
   * <简述>支付回调信息
   * <详细描述>
   * @author syf
   * @date 2024/12/16 14:34
   */

  @RequestMapping("/payOrder")
    public void payOrderNotify() throws IOException {

        //请求参数
        JSONObject params = requestKitBean.getReqParamJSON();

        String mchNo = params.getString("mchNo");
        String appId = params.getString("appId");
        String sign = params.getString("sign");
        MchApp mchApp = mchAppService.getById(appId);
        if(mchApp == null || !mchApp.getMchNo().equals(mchNo)){
            response.getWriter().print("app is not exists");
            return;
        }

        params.remove("sign");
        if(!JeepayKit.getSign(params, mchApp.getAppSecret()).equalsIgnoreCase(sign)){
            response.getWriter().print("sign fail");
            return;
        }

        JSONObject msg = new JSONObject();
        msg.put("state", params.getIntValue("state"));
        msg.put("errCode", params.getString("errCode"));
        msg.put("errMsg", params.getString("errMsg"));

        //推送到前端
        WsPayOrderServer.sendMsgByOrderId(params.getString("payOrderId"), msg.toJSONString());

        response.getWriter().print("SUCCESS");
    }

}
